using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Modules.NBrightEspace.Components;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

namespace DotNetNuke.Modules.NBrightEspace
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditNBrightEspace class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Estimates : EspaceModuleBase
    {

        #region Event Handlers

        private const string EntityTypeCode = "ESTIMATES"; // change for DB records


        override protected void OnInit(EventArgs e)
        {
            //Set base EntityTypeCode, MUST be done for all NBright child ctrls before OnInit
            base.EntityTypeCode = EntityTypeCode;
            
            base.OnInit(e);
            
            //initalize the repeater template based on what we want to see, a list or editing details.
            if (base.ItemId=="")
            {// itemid is blank so display the list
                rpData.Visible = false;

                //All list display functions are processed via the parent class, we just initiallize here.
                base.OnInitActivateList(true, true, MapPath(ControlPath));

            }
            else
            {// itemid is not blank, so display the detail template.

                base.OnInitDetail(rpData);


                var templateData = TemplCtrl.GetTemplateData("ARTICLES_Selected.html", Utils.GetCurrentCulture());
                templateData = TemplCtrl.ReplaceResourceString(templateData);
                rpArticle.ItemTemplate = new GenXmlTemplate(templateData);

                phArticleH.Controls.Add(new LiteralControl(TemplCtrl.GetTemplateData("ARTICLES_SelectedH.html", Utils.GetCurrentCulture())));
                phArticleF.Controls.Add(new LiteralControl(TemplCtrl.GetTemplateData("ARTICLES_SelectedF.html", Utils.GetCurrentCulture())));


            }

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack == false)
            {
                PageLoad();
            }
        }

        private void PageLoad()
        {
            try
            {

                if (UInfo.SelType == "client")
                {// return to control from selection page.
                    base.UpdateSelected("client");
                }

                if (UInfo.SelType == "article")
                {// return to control from selection page.
                    UpdateSelectedArticle();
                }

                if (base.ItemId=="")
                {// display list                    

                    //set default filter
                    if (String.IsNullOrEmpty(UInfo.SearchClearAfter))
                    {
                        UInfo.SearchFilters = " and (([xmlData].value('(genxml/checkbox/chkarchived)[1]', 'nvarchar(5)') collate Latin1_General_CI_AI != 'True'))";
                        UInfo.SearchOrderby = " Order by [xmlData].value('(genxml/textbox/dateestimate)[1]', 'nvarchar(50)') DESC ";
                        UInfo.Save();
                    }

                    base.BindListData();
                }
                else
                {// display the detail
                    base.DoDetail(rpData);

                    if (base.IsItemLocked(rpData))
                    {
                        //add message to update if lock is set by sombody else.
                        base.SetUpdateMsgIfLocked(rpData, "cmdUpdate1", Localization.GetString("LockMsg", LocalResourceFile));                        
                    }
                    else
                    {
                        base.SetLock();
                    }

                    //get article attached to this invoice                    
                    base.DoList(rpArticle, PortalId,ModuleId,EntityTypeCode + Convert.ToString(base.ItemId));
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        #endregion

        #region  "Events "

        protected void CtrlItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {

                var cArg = e.CommandArgument.ToString();
                NBrightInfo objInfo;

                switch (e.CommandName.ToLower())
                {
                    case "new":
                        UpdateData();
                        if (Page.IsValid)
                            Response.Redirect(EditUrl("itemid", "0", EntityTypeCode), true);
                        break;
                    case "update":
                        objInfo = UpdateData();
                        if (Page.IsValid)
                        {
                            ObjEspaceCtrl.CreateEstimatePdf(objInfo.ItemID, PortalSettings,MapPath(ControlPath));
                            Response.Redirect(EditUrl("itemid", objInfo.ItemID.ToString(""), EntityTypeCode), true);
                        }
                        break;
                    case "updateexit":
                        objInfo = UpdateData();
                        if (Page.IsValid)
                        {
                            ObjEspaceCtrl.CreateEstimatePdf(objInfo.ItemID, PortalSettings, MapPath(ControlPath));
                            Response.Redirect(EditUrl(EntityTypeCode));
                        }
                        break;
                    case "cancel":
                        Response.Redirect(EditUrl(EntityTypeCode));
                        break;
                    case "delete":
                        base.DeleteData(rpData);
                        if (Utils.IsNumeric(cArg))
                        {
                            base.DeleteArticleData(Convert.ToInt32(cArg));
                        }
                        Response.Redirect(EditUrl(EntityTypeCode));
                        break;
                    case "deletearticle":
                        if (Utils.IsNumeric(cArg))
                        {
                            ObjCtrl.Delete(Convert.ToInt32(cArg));
                        }
                        if (Page.IsValid)
                            Response.Redirect(EditUrl("itemid", Convert.ToString(base.ItemId), EntityTypeCode), true);
                        break;
                    case "selectclient":
                        UpdateData();
                    UInfo.SelType = "client";
                    UInfo.RtnSelUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.RtnUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.Save();
                        if (Page.IsValid)
                            Response.Redirect(EditUrl("ClientSel"));
                        break;
                    case "selectarticle":
                        UpdateData();
                    UInfo.SelType = "article";
                    UInfo.RtnSelUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.RtnUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.Save();
                        if (Page.IsValid)
                            Response.Redirect(EditUrl("ArticleSel"));
                        break;
                    case "addarticle":
                        UpdateData();
                        base.AddBlankEntity(EntityTypeCode + Convert.ToString(base.ItemId));
                        if (Page.IsValid)
                            Response.Redirect(EditUrl("itemid", Convert.ToString(base.ItemId), EntityTypeCode), true);
                        break;
                    case "recalc":
                        objInfo = UpdateData();
                        if (Page.IsValid)
                            ObjEspaceCtrl.CreateEstimatePdf(objInfo.ItemID, PortalSettings, MapPath(ControlPath));
                        Response.Redirect(EditUrl("itemid", Convert.ToString(base.ItemId), EntityTypeCode), true);
                        break;
                    case "createinvoice":
                        UpdateData();
                        if (Utils.IsNumeric(cArg))
                        {
                            CreateInvoice(Convert.ToInt32(cArg));
                        }
                        break;
                }
            }
            catch (Exception excep)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, excep);
            }

        }


        public override void EventListItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "printpdf":
                    OutputInvoicePdf(cArg, "estimateprintpdf");
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "printpdf2":
                    OutputInvoicePdf(cArg, "estimateprintpdfrtn");
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "pdf":
                    OutputInvoicePdf(cArg, "estimatepdf");
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "copy":
                    if (Utils.IsNumeric(cArg))
                    {
                        CopyEstimate(Convert.ToInt32(cArg));
                    }
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
            }
        }

        private void OutputInvoicePdf(string itemId, string pdfType)
        {
            if (Utils.IsNumeric(itemId))
            {
                var objCtrl = new EspaceController();
                var objInfo = ObjCtrl.Get(Convert.ToInt32(itemId));
                var fLink = GenXmlFunctions.GetGenXmlValue(pdfType, "hidden", objInfo.XMLData);
                if (fLink != "")
                {
                    fLink = System.Web.Hosting.HostingEnvironment.MapPath(fLink);
                    if (System.IO.File.Exists(fLink))
                    {
                        Utils.ForceDocDownload(fLink, GenXmlFunctions.GetGenXmlValue("EstimateRef", "hidden", objInfo.XMLData) + ".pdf", Response);
                    }
                }
            }
        }

        #endregion

        #region "presistance methods"


        private NBrightInfo UpdateData()
        {
            if (Page.IsValid)
            {
                var objDbInfo = GetData(); // get data before update.

                var objCtrl = new EspaceController();

                var objInfo = objCtrl.UpdateEstimate(Convert.ToInt32(base.ItemId), rpData, rpArticle, EntityTypeCode,PortalSettings);
                base.ItemId = Convert.ToString(objInfo.ItemID); // set base id, could be new record created.
                base.ReleaseLock(GetData(),true);

                return objInfo;
            }
            return null;
        }

        public void UpdateSelectedArticle()
        {
            var articleId = UInfo.SelItemId;
            UInfo.SelType = "";
            UInfo.Save();

            if ((Utils.IsNumeric(articleId)) & (Utils.IsNumeric(ItemId)))
            {

                var newid = base.AddBlankEntity(EntityTypeCode + Convert.ToString(base.ItemId));

                var objCInfo = ObjCtrl.Get(Convert.ToInt32(articleId));
                var objInfo = ObjCtrl.Get(Convert.ToInt32(newid));

                if (((objInfo != null)) & ((objCInfo != null)))
                {
                    // get xml format
                    var rp1 = GenXmlFunctions.InitRepeater(objInfo, TemplCtrl.GetTemplateData("ARTICLES_Selected.html", Utils.GetCurrentCulture()));
                    //Get format XML from new repeater so XML is created.
                    objInfo.XMLData = GenXmlFunctions.GetGenXml(rp1);

                    //Get XML data from both selected article and the new article
                    var xmlDoc = new XmlDataDocument();
                    var xmlCDoc = new XmlDataDocument();
                    xmlDoc.LoadXml(objInfo.XMLData);
                    xmlCDoc.LoadXml(objCInfo.XMLData);

                    //merge the selected article data into the new article xml.
                    GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtsummary");
                    GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtprice");
                    GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/dropdownlist/ddltax");
                    GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/dbltotalprice");

                    //assign to class and save to DB.
                    objInfo.XMLData = xmlDoc.OuterXml;
                    ObjCtrl.Update(objInfo);
                }
            }
        }

        private void CopyEstimate(int itemId)
        {
            var objInfo = ObjCtrl.Get(itemId);
            if (objInfo!=null)
            {
                //copy estimate
                objInfo.ItemID = -1;
                var newID = ObjCtrl.Update(objInfo);
                objInfo.ItemID = newID;

                // update Estimate Ref
                var xmlDoc = new XmlDataDocument();
                xmlDoc.LoadXml(objInfo.XMLData);
                GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/estimateref", "DE3" + objInfo.ItemID.ToString("000000") + "-" + Convert.ToString(DateTime.Now.Year).Substring(2, 2));
                objInfo.XMLData = xmlDoc.OuterXml;
                ObjCtrl.Update(objInfo);
                
                //copy Articles
                var l = ObjCtrl.GetList(-1,-1,EntityTypeCode + itemId.ToString(""));
                foreach (var dItem in l)
                {
                    dItem.ItemID = -1;
                    dItem.TypeCode = EntityTypeCode + newID.ToString("");
                    ObjCtrl.Update(dItem);
                }
            }
            
        }

        private void CreateInvoice(int estimateItemId)
        {
            var objInfo = ObjCtrl.Get(Convert.ToInt32(estimateItemId));
            if (objInfo != null)
            {
                //copy estimate
                objInfo.ItemID = -1;
                objInfo.TypeCode = "INVOICES";
                objInfo.XMLData = GenXmlFunctions.SetGenXmlValue(objInfo.XMLData, "genxml/checkbox/chkarchived", "False", false);
                var newID = ObjCtrl.Update(objInfo);
                objInfo.ItemID = newID;

                base.ReleaseLock(objInfo,true);

                ObjCtrl.Update(objInfo);

                //copy Articles
                var l = ObjCtrl.GetList(-1,-1,EntityTypeCode + estimateItemId.ToString(""));
                foreach (var dItem in l)
                {
                    dItem.ItemID = -1;
                    dItem.TypeCode = "INVOICES" + newID.ToString("");
                    ObjCtrl.Update(dItem);
                }
                Response.Redirect(EditUrl("itemid", Convert.ToString(newID), "INVOICES"), true);
            }

        }


        #endregion


    }

}